package com.wufun.overseas.main.base;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.multidex.MultiDex;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.papa91.arcapp.AppConfig;
import com.wufun.baselibrary.base.BaseApplication;
import com.wufun.baselibrary.download.CommonDownloadFactory;
import com.wufun.baselibrary.download.CommonDownloadTask;
import com.wufun.baselibrary.utils.AppInfoUtil;
import com.wufun.baselibrary.utils.FileUtils;
import com.wufun.baselibrary.utils.LogUtils;
import com.wufun.overseas.models.event.DownloadResultEvent;
import com.wufun.overseas.models.greendao.gen.DaoMaster;
import com.wufun.overseas.models.greendao.gen.DaoSession;
import com.wufun.overseas.models.greendao.gen.DotRequestTableDao;
import com.wufun.overseas.models.greendao.gen.DownLoadModelDao;
import com.wufun.overseas.tools.DownloadManager;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;

/**
 * Created by tangbingliang on 17/2/16.
 */

public class MyApplication extends BaseApplication {

    private SQLiteDatabase db;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private DownLoadModelDao mDownLoadModelDao;
    private DotRequestTableDao mDotRequestTableDao;
    private DaoMaster.DevOpenHelper mHelper;

    private String dbName;
    private String appRootPath;

    private CommonDownloadFactory factory;

    private String serverUid = "111111";//CLIENT
    private String clientUid = "222222";

    private static MyApplication mMyInstance = null;

    public static MyApplication getMyApplication(){
        return mMyInstance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mMyInstance = this;
        Fresco.initialize(this);
        initPath();
        setDatabase();
        initDataBaseOb();
        initDownload();
    }

    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    private void initDownload() {
        factory = CommonDownloadFactory.get();
        factory.setListener(new CommonDownloadFactory.DownloadListener() {
            @Override
            public void onDownloadStart(String url, String gameName) {
                EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_START, url));
            }

            @Override
            public void onDownloadWait(String url, long size) {
                DownloadManager.getInstance().updataDownloadTotalSize(url, size);
            }

            @Override
            public void onDownloadProgress(String url, int progress, String speed) {
                EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_PROGRESS, url, progress, speed));
            }

            @Override
            public void onDownloadFinish(String url, String gameName) {
                EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_FINISH, url, gameName));
            }

            @Override
            public void onDownloadError(String url, String gameName) {
                EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_ERROR, url, gameName));
            }

            @Override
            public void onDownloadStarZIP(String url, String gameName) {
                EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_STSRT_ZIP, url, gameName));
            }

            @Override
            public void onDownloadZIPProgress(String url, int progress, String speed) {
                EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_ZIP_PROGRESS, url, progress, speed));
            }

            @Override
            public void onDownloadZIPError(String url, String gameName) {
                EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_ZIP_FAIL, url, gameName));
            }

            @Override
            public void onDownloadStop(String url, String gameName) {
                EventBus.getDefault().post(new DownloadResultEvent(CommonDownloadTask.STATUS_STOP, url, gameName));
            }
        });
    }

    private void initPath() {
        dbName = AppInfoUtil.getAppPkName(this).substring(AppInfoUtil.getAppPkName(this).lastIndexOf(".")+1);
        appRootPath = FileUtils.SDPATH + dbName + "/";
        AppConfig.PRIVATE_PATH = appRootPath;
        AppConfig.APP_PATH = appRootPath;
        File file = new File(FileUtils.SDPATH, dbName);
        LogUtils.e("tbl>>>appRootPath:"+appRootPath);
        LogUtils.e("tbl>>>file.exists():"+file.exists());
        if (!file.exists()) {
            boolean bs = file.mkdirs();
            LogUtils.e("tbl>>>file.mkdirs():"+bs);
            if (!bs) {
                FileUtils.initPath(this);
                initPath();
            }
        }
    }

    private void initDataBaseOb() {
        mDownLoadModelDao = mDaoSession.getDownLoadModelDao();
        mDotRequestTableDao = mDaoSession.getDotRequestTableDao();
    }

    /**
     * 设置greenDao
     */
    private void setDatabase() {

        // 通过DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的SQLiteOpenHelper 对象。
        // 可能你已经注意到了，你并不需要去编写「CREATE TABLE」这样的 SQL 语句，因为greenDAO 已经帮你做了。
        // 注意：默认的DaoMaster.DevOpenHelper 会在数据库升级时，删除所有的表，意味着这将导致数据的丢失。
        // 所以，在正式的项目中，你还应该做一层封装，来实现数据库的安全升级。
        mHelper = new DaoMaster.DevOpenHelper(this, dbName, null);
        db =mHelper.getWritableDatabase();
        // 注意：该数据库连接属于DaoMaster，所以多个 Session 指的是相同的数据库连接。
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoSession getSession() {
        return mDaoSession;
    }

    public DownLoadModelDao getmDownLoadModelDao() {
        return mDownLoadModelDao;
    }

    public DotRequestTableDao getmDotRequestTableDao() {
        return mDotRequestTableDao;
    }

    public String getAppRootPath() {
        return appRootPath;
    }

    public String getDbName() {
        return dbName;
    }

    public String getServerUid() {
        return serverUid;
    }

    public String getClientUid() {
        return clientUid;
    }
}
